define(function(require, exports, module) {
    'use strict';
    
    
    var rk = require('rk');
    require('core/widgets/input/checkbox/widget');
    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');
    var rk_userService = require('userService');

    var currentPageUserId = SESSION.user.id;
    var currentPageUserName = SESSION.user.name;

    $.widget('rk.calOwnerSelCtrl', {
            val: null,
            ulObj: null,
            dropdownBtn: null,
            popupDiv: null,
            resultCon: null,
            nameInput: null,
            headTitle: null,
            isActive: false,
            currentUserId: currentPageUserId,
            _create: function(){
                var me = this;
                var elem = me.element;
                me.dropdownBtn = elem.find('.schedule_title');
                me.popupDiv = elem.find('.drop_div'); 
                me.dropdownBtn.click(function(){
                    if(!me.isActive)return;
                    if(!me.isVisible){
                        me.loadHtml();
                        me.popup();
                    }else{
                        me._hide();
                    }                
                    window.clearTimeout(me.hide_timer);
                });
                //scheduleUtil.bindEvent('dataInited', function(){
                    me.updateByCookie();
                    me.isActive = true;//must wait init-data, which containing recent-users
                //});             
            },
            scheduleColors: null,
            loaded:false,
            inited: false,
            isVisible:false,
            getUserId: function(){
                var me = this;
                return me.currentUserId;
            },
            popup: function (){
                var me = this;
                var elem = me.element;
                me._show();
                me.nameInput.focus();
                me._markCurrentUser();
            },
            cookie_updated: false,
            updateByCookie: function(){
                var me = this;
                var opt = me.options;
                if(me.cookie_updated)return;            
                var userId = SESSION.user.id;//scheduleUtil.getDisplaySettingByCookie('userId');
                scheduleUtil.setDisplaySetting('userId', userId);
                return;
                if(typeof userId != 'undefined'){
                    var uinfo = rk_userService.getUserInfo(userId);
                    if(uinfo && userId != currentPageUserId){
                        me._updateTitle(uinfo.name);
                        me._handleChange('cookie', userId, uinfo.name);
                    }
                }
                me.cookie_updated = true;
            },
            search_timer: null,
            search_count: 0,
            loadHtml: function(){
                var me = this;
                var opt = me.options;

                if(me.inited){
                    me._resetHtml();
                    me.displayRecentCollages();//always load
                    return;
                }
                var html = rk.templateText(require('oa/tmpl/schedule/page/template_scheduleOwnerSelector.tpl'));//template('template_scheduleOwnerSelector', {});
                me.popupDiv.html(html).css('position','absolute');
                me.resultCon = me.popupDiv.find('.rt-result'); 
                me.headTitle = me.popupDiv.find('.my_schedule_head');
                me.nameInput = me.popupDiv.find('input');
                me.resultUL = me.resultCon.find('.rt-collage-result').find('ul');
                me.recentUL = me.resultCon.find('.cooperate_people_list').find('ul');

                me.resultCon.beScroll();

                // me.popupDiv.bind('mouseleave', function(){
                //     //me._hide();
                // }).bind('mousemove', function(){
                //     //window.clearTimeout(me.hide_timer);
                // });
                me.popupDiv.bind('mousemove', function(){
                    window.clearTimeout(me.hide_timer);
                });
                $(document.body).bind('click', function(e){
                    var target = $(e.target);
                    if(target.parents('.my_schedule_list').size() > 0){return;}
                    else if(target.hasClass('my_schedule_list')){return;}
                    else if(target.parents('.schedule_title').size() > 0){return;}
                    else if(target.hasClass('schedule_title')){return;}
                    me.hide_timer = window.setTimeout(function(){ me._hide(); }, 150);
                });
                me.popupDiv.bind('scroll', function(){
                    window.clearTimeout(me.hide_timer);
                });
                me.popupDiv.bind('mouseup', function(){
                    window.clearTimeout(me.hide_timer);
                });

                me.headTitle.bind('click', function (){
                    scheduleUtil.setDisplaySetting('userId', currentPageUserId);
                    scheduleUtil.loadEvents();
                    me._markCurrentUser();
                    me._hide();
                    me._updateTitle(rk.i18n('SCHEDULE_2'));
                    me._handleChange('click', currentPageUserId, currentPageUserName);
                });            
                me.nameInput.bind('mousedown', function(){
                    window.clearTimeout(me.hide_timer);
                });
                me.nameInput.bind('focus', function(){
                    window.clearTimeout(me.hide_timer);
                });
                me.nameInput.bind('keyup', function(){
                    window.clearTimeout(me.search_timer);
                    var keyword = me.nameInput.val();
                    me.search_timer = window.setTimeout(function(){
                        me._searchCollages(keyword);
                    }, 120);                
                }).bind('blur', function(){
                    
                });
                me.resultCon.on('mousedown', 'li', function(){
                    var a = $(this).find('a');
                    var id = $(this).attr('user-id');
                    var name = a.find('span').text(); 
                    var icon = $(this).find('img').attr('src');
                    me.reloadEvents(id);
                    me._updateTitle(id == currentPageUserId ? rk.i18n('SCHEDULE_2') : name);
                    me._markCurrentUser();
                    me._hide();
                    rk_userService.updateRecentUserList({
                        id: id,
                        name: name,
                        icon: icon
                    });
                    me._handleChange('click', id, name);
                });
                me.displayRecentCollages();
                me.inited = true;
            },
            _handleChange: function(by, id, name){
                var me = this;
                var opt = me.options;
                if(me.currentUserId != id && opt.onChange)(opt.onChange)(id, name);
                if(by == 'click' && opt.onSelect)(opt.onSelect)(id, name);
                me.currentUserId = id;
            },
            reloadEvents: function(id){
                var me = this;
                scheduleUtil.setDisplaySetting('userId', id);
                scheduleUtil.loadEvents();
            },
            _getLiHtml: function(id, name, icon){
                var currentId = scheduleUtil.getDisplaySetting('userId');
                var html = '';
                html = html + '<li user-id="'+id+'"><a href="javascript:void(0);">' + 
                                    '<img src="'+(icon ? icon : '/img/default_face.png')+'">' + 
                                    '<span class="schedule-owner-item">'+name+'</span>'+
                                    (currentId == id ? '<span class="checked"></span>':'')+
                                    '</a></li>';
                return html;
            },
            displayRecentCollages: function(){
                var me = this;
                var users = rk_userService.getRecentUserList();
                var MAX = 5;            
                var container = me.popupDiv.find('.cooperate_people_list');
                if(!users || users.length == 0){
                    container.hide();
                    return;
                }
                container.show();
                var ul = container.find('ul');
                var html = '';
                var LEN = users.length;
                if(LEN > MAX)LEN = MAX;
                for(var i = 0; i < LEN; i++){
                    var user = users[i];
                    var id = user.id;
                    html = html + me._getLiHtml(user.id, user.name, user.icon);
                }
                ul.html(html);
            },
            _searchCollages: function(keyword){
                var me = this;
                var url = '/json/crm_search/all-users.action';
                me.search_count++;
                $.ajax({
                            url: url,
                            data: {
                                key: keyword,
                                pageNo: 1//
                            },
                            dataType: 'json'
                        })
                        .success(function( data ) {
                            me.search_count--;
                            if(me.search_count==0 && data)
                            display(data);
                        })
                        .error(function(){})
                        .done(function(){});

                function display(data){             
                    var users = data;
                    var ul = me.resultUL;
                    ul.html('');//clean
                    var html = '';
                    for(var i =0, len = users.length; i < len; i++){
                        var user = users[i];
                        var id = user.id;
                        var name = user.name;
                        var icon = user.icon;//me._getIconUrl(user.label);
                        html = html + me._getLiHtml(id, name, icon);
                    }
                    ul.html(html);
                    me.resultCon.scrollTop(0);
                }
            },
            _markCurrentUser: function(){
                var me = this;
                var currentId = scheduleUtil.getDisplaySetting('userId');
                var lis = me.popupDiv.find('li');
                ////(currentId == user.id ? '<span class="checked"></span>' : '')+
                lis.each(function(){
                    var a = $(this).find('a');
                    var id = $(this).attr('user-id');
                    a.find('span[class="checked"]').remove();
                    if(currentId == id){
                        a.append('<span class="checked"></span>');
                    }
                });
                if(currentPageUserId != currentId){
                    me.headTitle.find('span[class="checked"]').hide();
                }else{
                    me.headTitle.find('span[class="checked"]').show();
                }            
            },
            _resetHtml: function(){
                var me = this;
                me.resultUL.html('');
                me.nameInput.val('');
            },
            _show: function(){
                var me = this;
                var offset = $(me.dropdownBtn).offset();
                var height = $(me.dropdownBtn).height();
                me.popupDiv.css('left',0).css('top',50).css('display','block');
                me.isVisible = true;
            },
            hide_timer:null,
            _hide: function (){
                var me = this;
                me.popupDiv.css('display','none');
                me.isVisible = false;
                // window.clearTimeout(me.hide_timer);            
                // me.hide_timer = window.setTimeout(function(){
                //     me.popupDiv.css('display','none');
                // }, 200);
            },
            _updateTitle: function(name){
                var me = this;
                me.element.find('.schedule_title').html(name + rk.i18n('SCHEDULE_3') + '<i class="arrow_down"></i>');
            }
            
    });
});